// 会议管理系统 - 全局JS文件

// 设置axios默认配置
axios.defaults.headers.common['Content-Type'] = 'application/json';

// 页面加载时自动设置token
document.addEventListener('DOMContentLoaded', function() {
    // 如果当前是登录页，强制清理 token
    const currentPath = window.location.pathname;
    if (currentPath.startsWith('/login')) {
        localStorage.removeItem('token');
        delete axios.defaults.headers.common['Authorization'];
    }
    initAuth();
});

/**
 * 初始化认证状态
 */
function initAuth() {
    const currentPath = window.location.pathname;
    if (currentPath.startsWith('/login')) {
        // 登录页直接return，什么都不做，防止死循环和跳转
        return;
    }
    const token = localStorage.getItem('token');
    
    console.log('初始化认证状态，当前路径:', currentPath);
    
    // 设置axios默认Authorization头
    if (token) {
        console.log('找到token，设置Authorization头');
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        
        // 验证token有效性
        axios.get('/api/users/me')
            .then(response => {
                console.log('token有效，用户已登录:', response.data);
                updateNavigation(true);
                updateUserInfo(response.data);
                
                // 如果在登录页但已登录，跳转到主页
                if (currentPath === '/login' || currentPath === '/register' || currentPath === '/') {
                    window.location.href = '/rooms';
                }
            })
            .catch(error => {
                console.error('验证token失败:', error);
                // token无效，清除并显示未登录状态
                localStorage.removeItem('token');
                delete axios.defaults.headers.common['Authorization'];
                updateNavigation(false);
                // 如果已经在 /login、/register、/，不要再跳转
            });
    } else {
        // 未登录状态
        console.log('未找到token，用户未登录');
        updateNavigation(false);
        const isLoginPage = currentPath.startsWith('/login');
        const isRegisterPage = currentPath.startsWith('/register');
        const isRootPage = currentPath === '/';
        if (!isLoginPage && !isRegisterPage && !isRootPage) {
            window.location.href = '/login';
        }
    }
}

/**
 * 获取当前登录用户信息
 */
function fetchUserInfo() {
    axios.get('/api/users/me')
        .then(response => {
            // 更新用户信息显示
            updateUserInfo(response.data);
        })
        .catch(error => {
            // 如果返回401，说明token无效或过期，注销用户
            if (error.response && error.response.status === 401) {
                logout();
            }
        });
}

/**
 * 更新页面上的用户信息显示
 */
function updateUserInfo(user) {
    // 存储用户ID到localStorage
    if (user && user.id) {
        localStorage.setItem('user_id', user.id);
        console.log('用户ID已保存:', user.id);
    }
    
    const usernameElement = document.getElementById('username-display');
    if (usernameElement) {
        usernameElement.textContent = user.username;
    }
    
    // 根据用户角色显示/隐藏管理员功能
    if (user.is_admin) {
        document.querySelectorAll('.admin-only').forEach(el => {
            el.style.display = 'block';
        });
    }
}

/**
 * 更新导航菜单显示
 */
function updateNavigation(isLoggedIn) {
    const loginNav = document.getElementById('login-nav');
    const userNav = document.getElementById('user-nav');
    
    if (loginNav && userNav) {
        if (isLoggedIn) {
            loginNav.style.display = 'none';
            userNav.style.display = 'block';
        } else {
            loginNav.style.display = 'block';
            userNav.style.display = 'none';
        }
    }
}

/**
 * 处理登录表单提交
 */
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const errorMsg = document.getElementById('login-error');
    
    if (!username || !password) {
        if (errorMsg) errorMsg.textContent = '请输入用户名和密码';
        return;
    }
    
    // 准备表单数据
    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);
    
    // 发送登录请求
    axios.post('/token', formData, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        // 保存token并设置axios默认头
        localStorage.setItem('token', response.data.access_token);
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + response.data.access_token;
        
        // 获取用户信息并存储
        axios.get('/api/users/me')
            .then(userResponse => {
                console.log('登录成功，获取到用户信息:', userResponse.data);
                // 存储用户ID
                localStorage.setItem('user_id', userResponse.data.id);
                // 跳转到仪表盘
                window.location.href = '/dashboard';
            })
            .catch(userError => {
                console.error('获取用户信息失败:', userError);
                // 即使获取用户信息失败，也允许用户登录
                window.location.href = '/dashboard';
            });
    })
    .catch(error => {
        let message = '登录失败，请检查用户名和密码';
        if (error.response && error.response.data && error.response.data.detail) {
            message = error.response.data.detail;
        }
        if (errorMsg) errorMsg.textContent = message;
    });
}

/**
 * 处理注册表单提交
 */
function handleRegister(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    const errorMsg = document.querySelector('.alert-container');
    
    if (errorMsg) errorMsg.innerHTML = '';

    if (!username || !email || !password) {
        if (errorMsg) errorMsg.innerHTML = '<div class="alert alert-danger">请填写所有必填字段</div>';
        return;
    }
    
    if (!/^\S+@\S+\.\S+$/.test(email)) {
        if (errorMsg) errorMsg.innerHTML = '<div class="alert alert-danger">请输入有效的邮箱地址</div>';
        return;
    }
    
    if (password !== confirmPassword) {
        if (errorMsg) errorMsg.innerHTML = '<div class="alert alert-danger">两次密码输入不一致</div>';
        return;
    }
    
    axios.post('/api/users/register', {
        username: username,
        email: email,
        password: password
    })
    .then(response => {
        window.location.href = '/login?registered=true';
    })
    .catch(error => {
        let message = '注册失败，请稍后再试';
        if (error.response && error.response.data && error.response.data.detail) {
            if (typeof error.response.data.detail === 'string') {
                message = error.response.data.detail;
            } else if (typeof error.response.data.detail === 'object') {
                message = JSON.stringify(error.response.data.detail);
            } else {
                message = String(error.response.data.detail);
            }
        }
        if (errorMsg) errorMsg.innerHTML = `<div class="alert alert-danger">${message}</div>`;
    });
}

/**
 * 退出登录
 */
function logout() {
    localStorage.clear();
    delete axios.defaults.headers.common['Authorization'];
    window.location.replace('/login');
}

/**
 * 初始化退出登录按钮
 */
function initLogoutButton() {
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function(e) {
            e.preventDefault();
            logout();
        });
    }
}

// 导出函数
window.handleLogin = handleLogin;
window.handleRegister = handleRegister;
window.logout = logout;
window.checkAuth = initAuth;
window.initLogoutButton = initLogoutButton;

function getStatistics() {
    axios.get('/api/rooms/')
    .then(response => {
        document.getElementById('availableRoomCount').innerText = response.data.rooms.length;
    })
    .catch(error => {
        console.error('获取会议室统计数据失败:', error);
    });
} 